package com.ktgj.customer.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.common.base.Strings;
import com.ktgj.common.core.utils.HttpClientUtil;
import com.ktgj.customer.domain.Insurance.axModel.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.beans.XMLEncoder;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * 安心自助理赔 （机票）
 */
public class AutoClaimController {

    private final String MechanismVcode = "123456";
    private final String url = "https://antx11.95303.com/com.isoftstone.iics.bizsupport.epartner/autoClaimProcess/jsj";
    private final String ComId = "EC16070003";

    public Object autoClaim(AutoClaim autoClaim, Header header, AutoClaimCvrg autoClaimCvrg) throws UnsupportedEncodingException {
        String requestStr = AutoClaimRequest(autoClaim, header, autoClaimCvrg);
        String strResponse = "";
        String md5Request = getHash3(MechanismVcode + requestStr, "MD5");
        String comId = ComId;
        strResponse = HttpClientUtil.doPostXmlStream(url + "?" + "sign=" + md5Request + "&comId=" + comId, requestStr);
        Object objRes = null;
        String policyRemark = "安心接口未返回响应结果";
        if (!Strings.isNullOrEmpty(strResponse)) {
            objRes = ResponseAutoClaim(strResponse);
            policyRemark = strResponse;
        }
        return objRes;
    }

    public Object ResponseAutoClaim(String responseStr) {
        responseStr =
                responseStr.replace("autoClaim", "AutoClaim")
                        .replace("<package>", "<AutoClaim>")
                        .replace("</package>", "</AutoClaim>")
                        .replace("<packageList>", "<AutoClaim>\r\n<packageList>") + "</AutoClaim>";
        //AXAutoClaimResponse response = (AXAutoClaimResponse)GetModel(responseStr, typeof(Model.AXAutoClaim.AXAutoClaimResponse));

        List<AutoClaimReturn> axAutoClaimList = new ArrayList<>();
        AutoClaimReturn autoClaimReturn = new AutoClaimReturn();
        axAutoClaimList.add(autoClaimReturn);
        ResponseHeader responseHeader = new ResponseHeader();
        AutoClaimResponsePackage autoClaimResponsePackage = new AutoClaimResponsePackage();
        autoClaimResponsePackage.header = responseHeader;
        autoClaimResponsePackage.response = axAutoClaimList;
        List<AutoClaimResponsePackage> autoClaimResponsePackageList = new ArrayList<>();
        autoClaimResponsePackageList.add(autoClaimResponsePackage);
        AXAutoClaimResponse response = new AXAutoClaimResponse();
        response.packageList = autoClaimResponsePackageList;
        return response;

    }

    /*public static <T> String formatXML(T entity) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(out));
        encoder.writeObject(entity);
        encoder.close();
        return out.toString();
    }*/

    /**
     * md5加密
     */
    public static String getHash3(String source, String hashType) throws UnsupportedEncodingException {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        StringBuilder sb = new StringBuilder();
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance(hashType);
            md5.update(source.getBytes("UTF-8"));
            byte[] encryptStr = md5.digest();
            for (int i = 0; i < encryptStr.length; i++) {
                int iRet = encryptStr[i];
                if (iRet < 0) {
                    iRet += 256;
                }
                int iD1 = iRet / 16;
                int iD2 = iRet % 16;
                sb.append(hexDigits[iD1] + "" + hexDigits[iD2]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String AutoClaimRequest(AutoClaim autoClaim, Header header, AutoClaimCvrg autoClaimCvrg) {
        PackAge packAge = new PackAge();
        RequestAutoClaim requestAutoClaim1 = new RequestAutoClaim();

        packAge.setHeader(header);
        autoClaim.autoClaimCvrg = autoClaimCvrg;
        requestAutoClaim1.autoClaim = autoClaim;
        packAge.setRequest(requestAutoClaim1);

        //序列化
        XmlMapper xmlMapper = new XmlMapper();

        String str = null;
        try {
            String xmlStr = xmlMapper.writeValueAsString(packAge);
            xmlStr = xmlStr.replaceAll("PackAge", "package");
            str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><packageList>" + xmlStr + "</packageList>";
            //str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + xmlStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

     /**
      * 判断推送的订单是否存在及状态
      * */
   /* public boolean CheckReceiveClaimOrder(int delayClaimOrderId, AxClaimStatus status)
    {
        boolean result = false;
        String sql = "select d.state from t_c_delayinsurance d where d.delayinsurance_id=:delayinsurance_id";
        using (OracleConnection con = new OracleConnection(OracleDB.strOracleConn))
        {
            con.Open();
            using (OracleCommand command = con.CreateCommand())
            {
                command.Parameters.Clear();
                command.Parameters.Add("delayinsurance_id", OracleType.Int32).Value = delayClaimOrderId;
                command.CommandText = sql;
                using (OracleDataReader ruili = command.ExecuteReader())
                {
                    if (ruili.HasRows)
                    {
                        while (ruili.Read())
                        {
                            string state = ruili["state"].ToString();
                            status = (AxClaimStatus)Enum.Parse(typeof(AxClaimStatus), state);
                        }
                        result = true;
                    }
                }
            }
        }
        return result;
    }

    *//**
     * TODO 接收誉好发送的理赔验证结果
     * @param claimInfo
     *//*
    public String ReceiveClaimVerify(String claimInfo)
    {
        YuHaoClaimVerify claimVerify = JSON.parseObject(claimInfo, YuHaoClaimVerify.class);

        if (Strings.isNullOrEmpty(claimVerify.ChannelRequestSeq))
        {
            return "ChannelRequestSeq为null";
        }
        *//*int jsjId = Integer.parseInt(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ(.*)-.*-.*")[0].Groups[1].Value);
        int delayInsuaranceId = Integer.parseInt(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ.*-.*-(.*)")[0].Groups[1].Value);
        String insno = String.valueOf(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ.*-(.*)-")[0].Groups[1].Value);*//*

        int jsjId = Integer.parseInt(String.valueOf(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ(.*)-.*-.*")));
        int delayInsuaranceId = Integer.parseInt(String.valueOf(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ.*-.*-(.*)")));
        String insno = String.valueOf(Pattern.matches(claimVerify.ChannelRequestSeq, "JSSJ.*-(.*)-"));

        AxClaimStatus orderStatus = AxClaimStatus.Init;
        if (!insuranceRecordDao.CheckReceiveClaimOrder(delayInsuaranceId, orderStatus))
        {
            return "该订单不存在";
        }
        if (orderStatus == AxClaimStatus.Auditing || orderStatus == AxClaimStatus.PaySuccess)
        {
            return "重复推送数据，该订单已经验证理赔成功了";
        }
        if (Strings.isNullOrEmpty(claimVerify.ClaimStatus))
        {
            return "数据错误，理赔验证状态为空";
        }
        try
        {
                // 更新订单状态 及 向用户发送短信
            String smsContent = "";
            //更新理赔订单订单表中的订单的状态 理赔订单提交成功和 提交失败状态
            YuHaoInsuranceEnums.YuhaoClaimResultDesc claimStatus = (YuHaoInsuranceEnums.YuhaoClaimResultDesc)Enum.Parse(typeof(YuHaoInsuranceEnums.YuhaoClaimResultDesc), claimVerify.ClaimStatus);
            AxClaimStatus status = AxClaimStatus.AuditingFailed;
            if (claimStatus == YuHaoInsuranceEnums.YuhaoClaimResultDesc.等待打款)
            {
                status = AxClaimStatus.Auditing;
            }
            -------------根据理赔订单号（主键）更新理赔的订单状态及说明------
            insuranceRecordDao.UpdateInsuranceClaimStatus(status, claimVerify.ClaimStatusDesc, delayInsuaranceId);
            JMember.SDK.JModels.DaXiangClaimResultRequest request = new JMember.SDK.JModels.DaXiangClaimResultRequest()
            {
                CustomerId = jsjId,
                DelayClaimOrderId = delayInsuaranceId,
                ClaimStatus = (JMember.SDK.Enums.EnumDef.APIEnum.ClaimStatus)Enum.Parse(typeof(JMember.SDK.Enums.EnumDef.APIEnum.ClaimStatus), ((int)status).ToString())
            };
            ------------------异步委托--------------
            Action<JMember.SDK.JModels.DaXiangClaimResultRequest> act = new Action<JMember.SDK.JModels.DaXiangClaimResultRequest>(PushClaimResult);
            act.BeginInvoke(request, null, null);
            //JMember.SDK.JClients.JMemberClient client = new JMember.SDK.JClients.JMemberClient();
            //client.DaXiangClaimResult(request);
        }
        catch (Exception ex)
        {
            throw new System.Exception("数据异常，处理失败");
            CommonMethod.WriteEsLog(new Log4JSJ.LogDto()
            {
                Request = claimInfo,
                Response = "数据库保存失败，报错信息：" + ex.toString(),
                Level = Log4JSJ.EnumHelper.Level.Fatal
            }, InsuranceCategory.DXFlightInsurance);
        }
        return null;
    }*/


}
